<template>
  <div v-if="isDev" class="dev-tools">
    <div class="dev-tools-toggle" @click="togglePanel">
      <n-icon size="20">
        <CodeOutline />
      </n-icon>
    </div>
    
    <div v-show="showPanel" class="dev-tools-panel">
      <div class="dev-tools-header">
        <h3>开发工具</h3>
        <n-button quaternary circle size="small" @click="togglePanel">
          <template #icon>
            <n-icon><CloseOutline /></n-icon>
          </template>
        </n-button>
      </div>
      
      <div class="dev-tools-content">
        <div class="dev-section">
          <h4>页面信息</h4>
          <div class="dev-info">
            <p><strong>当前路由:</strong> {{ currentRoute.name }}</p>
            <p><strong>路径:</strong> {{ currentRoute.path }}</p>
            <p><strong>窗口大小:</strong> {{ windowSize.width }} × {{ windowSize.height }}</p>
            <p><strong>鼠标位置:</strong> {{ mousePosition.x }}, {{ mousePosition.y }}</p>
          </div>
        </div>
        
        <div class="dev-section">
          <h4>系统状态</h4>
          <div class="dev-info">
            <p><strong>在线状态:</strong> {{ isOnline ? '在线' : '离线' }}</p>
            <p><strong>网络类型:</strong> {{ networkType }}</p>
            <p><strong>内存使用:</strong> {{ memoryInfo }}</p>
          </div>
        </div>
        
        <div class="dev-section">
          <h4>快捷操作</h4>
          <div class="dev-actions">
            <n-button size="small" @click="reloadPage">刷新页面</n-button>
            <n-button size="small" @click="clearStorage">清除缓存</n-button>
            <n-button size="small" @click="toggleTheme">切换主题</n-button>
            <n-button size="small" @click="exportLogs">导出日志</n-button>
          </div>
        </div>
        
        <div class="dev-section">
          <h4>元素检查 💡</h4>
          <div class="dev-info">
            <p><strong>VConsole:</strong> 点击右下角绿色按钮</p>
            <p><strong>Element标签:</strong> 查看页面结构</p>
            <p><strong>选择元素:</strong> 点击元素查看属性</p>
          </div>
          <div class="dev-actions">
            <n-button size="small" @click="openVConsole">打开VConsole</n-button>
            <n-button size="small" @click="toggleElementInspect">元素选择模式</n-button>
          </div>
        </div>
        
        <div class="dev-section">
          <h4>控制台日志</h4>
          <div class="dev-console">
            <div v-for="(log, index) in consoleLogs" :key="index" class="log-item" :class="log.type">
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useThemeStore } from '@/store'
import { CodeOutline, CloseOutline } from '@vicons/ionicons5'

const isDev = computed(() => import.meta.env.DEV)
const showPanel = ref(false)
const currentRoute = useRoute()
const themeStore = useThemeStore()

// 简化的状态管理，避免@vueuse/core依赖问题
const windowSize = ref({ width: window.innerWidth, height: window.innerHeight })
const mousePosition = ref({ x: 0, y: 0 })
const isOnline = ref(navigator.onLine)

// 更新窗口大小
const updateWindowSize = () => {
  windowSize.value = { width: window.innerWidth, height: window.innerHeight }
}

// 更新鼠标位置
const updateMousePosition = (e: MouseEvent) => {
  mousePosition.value = { x: e.clientX, y: e.clientY }
}

// 监听事件
if (isDev.value) {
  window.addEventListener('resize', updateWindowSize)
  window.addEventListener('mousemove', updateMousePosition)
  window.addEventListener('online', () => isOnline.value = true)
  window.addEventListener('offline', () => isOnline.value = false)
}

const networkType = computed(() => {
  return (navigator as any)?.connection?.effectiveType || '未知'
})

const memoryInfo = computed(() => {
  const memory = (performance as any)?.memory
  if (memory) {
    const used = (memory.usedJSHeapSize / 1024 / 1024).toFixed(2)
    const total = (memory.totalJSHeapSize / 1024 / 1024).toFixed(2)
    return `${used}MB / ${total}MB`
  }
  return '不支持'
})

// 控制台日志
const consoleLogs = ref<Array<{type: string, message: string, time: string}>>([])

// 拦截console方法
const originalConsole = {
  log: console.log,
  warn: console.warn,
  error: console.error,
  info: console.info
}

const interceptConsole = () => {
  const addLog = (type: string, args: any[]) => {
    const message = args.map(arg => {
      if (typeof arg === 'object' && arg !== null) {
        try {
          // 安全地序列化对象，避免循环引用
          return JSON.stringify(arg, (key, value) => {
            // 跳过可能导致循环引用的属性
            if (key === 'dep' || key === 'computed' || key === '__v_isRef' || key === '__v_isReactive') {
              return '[Circular Reference]'
            }
            // 如果是函数，显示函数名
            if (typeof value === 'function') {
              return `[Function: ${value.name || 'anonymous'}]`
            }
            // 如果是DOM元素，显示标签名
            if (value && value.nodeType) {
              return `[DOM Element: ${value.tagName || 'Unknown'}]`
            }
            return value
          })
        } catch (error) {
          // 如果序列化失败，返回对象的字符串表示
          return `[Object: ${arg.constructor?.name || 'Unknown'}]`
        }
      }
      return String(arg)
    }).join(' ')
    
    consoleLogs.value.unshift({
      type,
      message,
      time: new Date().toLocaleTimeString()
    })
    
    // 保持最多50条日志
    if (consoleLogs.value.length > 50) {
      consoleLogs.value.pop()
    }
  }
  
  console.log = (...args) => {
    originalConsole.log(...args)
    addLog('log', args)
  }
  
  console.warn = (...args) => {
    originalConsole.warn(...args)
    addLog('warn', args)
  }
  
  console.error = (...args) => {
    originalConsole.error(...args)
    addLog('error', args)
  }
  
  console.info = (...args) => {
    originalConsole.info(...args)
    addLog('info', args)
  }
}

// 开发环境下拦截console
if (isDev.value) {
  interceptConsole()
}

const togglePanel = () => {
  showPanel.value = !showPanel.value
}

const reloadPage = () => {
  location.reload()
}

const clearStorage = () => {
  localStorage.clear()
  sessionStorage.clear()
  console.log('缓存已清除')
}

const toggleTheme = () => {
  themeStore.toggleTheme()
}

const exportLogs = () => {
  const logs = consoleLogs.value.map(log => 
    `[${log.time}] ${log.type.toUpperCase()}: ${log.message}`
  ).join('\n')
  
  const blob = new Blob([logs], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `console-logs-${Date.now()}.txt`
  a.click()
  URL.revokeObjectURL(url)
}

const openVConsole = () => {
  // 查找并点击VConsole按钮
  const vcBtn = document.querySelector('#__vconsole .vc-switch') as HTMLElement
  if (vcBtn) {
    vcBtn.click()
    console.log('✅ VConsole已打开！点击Element标签可以检查页面元素')
  } else {
    console.log('❌ VConsole按钮未找到，请检查是否已加载')
  }
}

const toggleElementInspect = () => {
  console.log('💡 元素检查提示：')
  console.log('1. 点击右下角绿色按钮打开VConsole')
  console.log('2. 点击Element标签查看页面结构')
  console.log('3. 点击任意页面元素查看其属性和样式')
  console.log('4. 可以在Console标签中输入JavaScript代码调试')
  
  // 尝试自动打开VConsole
  openVConsole()
}

// 快捷键支持
const handleKeyPress = (e: KeyboardEvent) => {
  if (e.ctrlKey && e.shiftKey && e.key === 'D') {
    e.preventDefault()
    togglePanel()
  }
}

// 挂载时添加快捷键监听
if (isDev.value) {
  document.addEventListener('keydown', handleKeyPress)
}
</script>

<style scoped>
.dev-tools {
  position: fixed;
  z-index: 9999;
}

.dev-tools-toggle {
  position: fixed;
  bottom: 80px;
  left: 20px;
  width: 40px;
  height: 40px;
  background: linear-gradient(45deg, #ff006e, #8338ec);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  z-index: 1000;
}

.dev-tools-toggle:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

.dev-tools-panel {
  position: fixed;
  bottom: 130px;
  left: 20px;
  width: 350px;
  max-height: 400px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  z-index: 1001;
}

.dev-tools-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  background: linear-gradient(45deg, rgba(255, 0, 110, 0.1), rgba(131, 56, 236, 0.1));
}

.dev-tools-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.dev-tools-content {
  max-height: 430px;
  overflow-y: auto;
  padding: 16px;
}

.dev-section {
  margin-bottom: 20px;
}

.dev-section h4 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 600;
}

.dev-info p {
  margin: 4px 0;
  font-size: 12px;
  color: #555;
}

.dev-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.dev-console {
  max-height: 150px;
  overflow-y: auto;
  background: #f5f5f5;
  border-radius: 6px;
  padding: 8px;
}

.log-item {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 11px;
  line-height: 1.4;
}

.log-time {
  color: #888;
  flex-shrink: 0;
}

.log-message {
  color: #333;
  word-break: break-all;
}

.log-item.error .log-message {
  color: #ff4d4f;
}

.log-item.warn .log-message {
  color: #faad14;
}

.log-item.info .log-message {
  color: #1890ff;
}

/* 响应式 */
@media (max-width: 768px) {
  .dev-tools-panel {
    width: 300px;
    left: 10px;
    bottom: 120px;
  }
  
  .dev-tools-toggle {
    left: 10px;
    bottom: 70px;
  }
}
</style> 